// pages/todos/todos.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 文本框数据模式
    todo: '',
    // 任务清单
    todos: [
      {
        name: '学习HTML',
        completed: true
      },
      {
        name: '学习CSS',
        completed: false
      },
      {
        name: '学习JavaScript',
        completed: false
      }
    ],
    leftCount: 2,
    allCompleted: false
  },
  todoHandle: function(e) {
    this.setData({
      todo: e.detail.value
    })
  },
  addHandle: function(e) {
    if (!this.data.todo) return
    var item = {
      completed: false,
      name: this.data.todo
    }
    var newTodos = this.data.todos
    newTodos.push(item)
    this.setData({
      todo: '',
      todos: newTodos,
      leftCount: this.data.leftCount + 1
    })
  },
  deleteHandle: function(e) {
    var newTodos = this.data.todos
    var leftCount = this.data.leftCount
    if (!newTodos[e.target.dataset.index].completed) {
      leftCount = leftCount - 1
    }
    newTodos.splice(e.target.dataset.index, 1)
    this.setData({
      todos: newTodos,
      leftCount: leftCount
    })
  },
  completedHandled: function(e) {
    // var newTodos = this.data.todos
    // newTodos[e.target.dataset.index].completed = !newTodos[e.target.dataset.index].completed
    this.data.todos[e.target.dataset.index].completed = !this.data.todos[e.target.dataset.index].completed
    var leftCount = this.data.leftCount
    if (this.data.todos[e.target.dataset.index].completed) {
      leftCount = leftCount - 1
    } else {
      leftCount = leftCount + 1
    }
    this.setData({
      todos: this.data.todos,
      leftCount: leftCount
    })
  },
  toggleAll: function(e) {
    this.data.allCompleted = !this.data.allCompleted
    var todos = this.data.todos
    var that = this
    todos.forEach(function(item) {
      item.completed = that.data.allCompleted
    })
    var leftCount = this.data.leftCount
    if (this.data.allCompleted) {
      leftCount = 0
    } else {
      leftCount = todos.length
    }
    this.setData({
      todos: todos,
      leftCount: leftCount   
    })
  },
  clearHandle: function() {
    // var todos = this.data.todos
    // todos.forEach(function(item, index) {
    //   if (item.completed) {
    //     todos.splice(index, 1)
    //   }
    // })
    var todos = this.data.todos.filter(item => !item.completed)
    this.setData({
      todos: todos
    })
  }
})